<?php

/**
 * user actions.
 *
 * @package    jiazhang
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }
  
  public function executeLogout(sfWebRequest $request){
        $this->getUser()->setAuthenticated(false);
        $this->getUser()->setAttribute('user_id', 0);
        $this->getUser()->setAttribute('user_cover', 0);
        $this->redirect('@new_index');
  }
  
  //登入
  public function executeLogin(sfWebRequest $request){
      $this->getResponse()->setTitle('用户登录 - 壹童学');
      if($this->getUser()->isAuthenticated()) {
            $this->redirect('@new_index');
      } 
      
      if($request->isMethod('POST')){
          $phone = floatval($request->getParameter('phone',0));
          $password = trim($request->getParameter('password',0));
          
          if(strlen($phone) != 11){
              $this->getUser()->setFlash('phone-error','手机号码格式错误，请检查！');
          }elseif(strlen($password) < 8){
              $this->getUser()->setFlash('password-error','密码错误，请检查！');
          }else{
              $has_user = Doctrine::getTable('User')->findOneByPhone($phone);
              
              if($has_user){
                  
                  if($has_user->getStatus() == 0){
                      $this->getUser()->setFlash('password-error','用户被禁用，请联系管理员！');
                      return;
                  }
                  
                  $user_password = $has_user->getPassword();
                  
                  if(md5($password) == $user_password){
                      $this->getUser()->setAuthenticated(true);
                      $this->getUser()->setAttribute('user_id', $has_user->getId());
                      $this->getUser()->setAttribute('user_cover', $has_user->getCover());
                      $this->getUser()->setAttribute('nick_name', $has_user->getNickname());
                      $this->getUser()->setAttribute('phone', $has_user->getPhone());
                      $this->redirect('@new_index');
                  }else{
                      $this->getUser()->setFlash('password-error','用户密码错误，请检查！');
                      return;
                  }
                  
              }else{
                  $this->getUser()->setFlash('phone-error','用户不存在，请检查！');
                  return;
              }
          }
          
      }
  }
  
  public function executeReg(sfWebRequest $request)
  {
      $this->getResponse()->setTitle('用户注册 - 壹童学');
      if($this->getUser()->isAuthenticated()) {
            $this->redirect('@new_index');
      } 
      
      if($request->isMethod('POST')){
          $phone = floatval($request->getParameter('phone',0));
          $code = (int)$request->getParameter('phone_code',0);
          $password = trim($request->getParameter('password',0));
          $password_2 = trim($request->getParameter('password_two',0));
          
          if(strlen($phone) != 11){
              $this->getUser()->setFlash('phone-error','填写错误，请检查！');
          }elseif(strlen($code) != 6){
              $this->getUser()->setFlash('code-error','填写错误，请检查！');
          }elseif(strlen($password) < 8 || strlen($password_2) < 8){
              $this->getUser()->setFlash('password-error','密码长度错误，请检查！');
          }elseif($password != $password_2){
              $this->getUser()->setFlash('password-2-error','两次密码不一致，请检查！');
          }else{
            
            $has_user = Doctrine::getTable('User')->findOneByPhone($phone);  
            
            if($has_user){
                $this->getUser()->setFlash('phone-error','手机号已经注册！');
            }else{
                //@tudo: 检查验证码是否失效，失效时间为5分钟
                $sms = Doctrine::getTable('SmsMessage')->createQuery()->where('phone = ?',$phone)->andWhere("code = ?",$code)->andWhere('is_use = 0')->execute();
                if(count($sms) == 1 ){
                    $sms = $sms->getFirst();
                    $sms->setIsUse(1)->save();
                    $user = new User();
                    $user->setPhone($phone)->setPassword(md5($password))->setCover('')->save();
                    $user->getUserAttr();
                    $this->getUser()->setAttribute('user_id', $user->getId());
                    $this->getUser()->setAttribute('user_cover', '');
                    $this->getUser()->setAttribute('nick_name', '');
                    $this->getUser()->setAttribute('phone', $user->getPhone());
                    $this->getUser()->setAuthenticated(true);
                }

                $this->redirect('user/reg_2');
              }
          }
      }
  }
  
  //注册第二步
  public function executeReg_2(sfWebRequest $request){
      $this->getResponse()->setTitle('完善资料 - 用户注册 - 壹童学');
      //@tudo:这一步可以考虑通过要求用户登入来实现
      if(!$this->getUser()->isAuthenticated()) {
            $this->redirect('@new_index');
      } 
      
      $user_id = $this->getUser()->getAttribute('user_id',0);
      $this->user_childs = Doctrine::getTable('UserChild')->findByUserId($user_id);
  }
  
  //完善资料保存
  public function executeComplete_info(sfWebRequest $request){
      if($request->isMethod('POST')){
          $cover = $request->getParameter('cover_url','');
          $role = (int)$request->getParameter('role',1);
          $province = $request->getParameter('province','');
          $city = $request->getParameter('city');
          $nickname = trim($request->getParameter('nickname',''));
          $user_id = $this->getUser()->getAttribute('user_id');
          $user = Doctrine::getTable('User')->findOneById($user_id);
          $user->setNickname($nickname)->setRole($role)->setCover($cover)->setProvince($province)->setCity($city)->save();
          $this->getUser()->setAttribute('user_cover', $cover);
          $this->getUser()->setAttribute('nick_name', $nickname);
          $this->redirect('@new_index');
      }
  }
  
  #用户头像处理
//**  The file bdlogo.gif was successfully uploaded with a response of true:array(5) {
//  ["name"]=>
//  string(10) "bdlogo.gif"
//  ["type"]=>
//  string(24) "application/octet-stream"
//  ["tmp_name"]=>
//  string(49) "I:\xampp-win32-5.6.8-0-VC11\xampp\tmp\php2359.tmp"
//  ["error"]=>
//  int(0)
//  ["size"]=>
//  int(1575)
//}
  public function executeCover(sfWebRequest $request){
      sfConfig::set('sf_web_debug',false);

      if($request->isMethod('POST')){
          $user_id = $this->getUser()->getAttribute('user_id',0);
          $file = $request->getFiles('Filedata');
          
          if($user_id == 0 && $file['error'] == 4){
              exit();
          }
          
          $file_name = $file['name'];
          $file_ext_tmp = explode('.', $file_name);
          $file_ext = $file_ext_tmp[count($file_ext_tmp)-1];
          $allow_file_type = array('jpg','bmp','png','gif','jpeg');
          
          if(in_array($file_ext, $allow_file_type)){
             $year = date('Y',time());
             $month = date('m',time());
             $day = date('d',time());
             $save_file_name = $year.'_'.$month.'_'.$day.'_'.substr(md5(time()+rand(0,999)),25).'.'.$file_ext;
             $upyun_save_path = '/user/cover/'.$user_id.'/'.$save_file_name;
             $upyun = new UpYun(sfConfig::get('app_upyun_space'),sfConfig::get('app_upyun_user') , sfConfig::get('app_upyun_pwd'));
             
             try {
                $fh = fopen($file['tmp_name'], 'rb');
                $rsp = $upyun->writeFile($upyun_save_path, $fh, True);   // 上传图片，自动创建目录
                fclose($fh);
                $image_url=  sfConfig::get('app_img_url').$upyun_save_path;
                $json = new Services_JSON();
                $return_data = array('error' => 0, 'url' => $image_url);
                return $this->renderText($json->encode($return_data));
                exit();
            } catch(Exception $e) {
                echo $e->getCode();
                echo $e->getMessage();
            }
            
          }else{
              $return_data = array('error' => 1, 'url' => '文件类型错误！');
              //error 文件类型错误
              $json = new Services_JSON();
              return $this->renderText($json->encode($return_data));
              exit();
          }
      }
  }

  
  public function executeDel_child(sfWebRequest $request){
      if($request->isMethod('POST')){
          $user_id = $this->getUser()->getAttribute('user_id',0);
          $child_id = (int)$request->getParameter('child_id',0);
          
          if($user_id == 0 ||$child_id == 0) exit();
          $has_child = Doctrine::getTable('UserChild')->createQuery()->where('user_id = ?',$user_id)->andWhere('id = ?',$child_id)->execute();
          
          if($has_child){
              $has_child->delete();
              return $this->renderText(json_encode(array('success'=>1)));
          }else{
              return $this->renderText(json_encode(array('success'=>0)));
          }
          return false;
      }
  }
  
  //增加用户的孩子
  public function executeAdd_child(sfWebRequest $request){
      
      if($request->isMethod('POST')){
          $user_id = $this->getUser()->getAttribute('user_id',0);
          $year = (int)$request->getParameter('year',0);
          $month = (int)$request->getParameter('month',0);
          $sex = (int)$request->getParameter('sex',3);
          $current_year = date('Y');
          
          if($user_id == 0 || ($year == 0 || $year > $current_year ) || ( $month <= 0 || $month > 12 ) || $sex == 3) exit();
          
          $child = new UserChild();
          $child->setUserId($user_id)->setYear($year)->setMonth($month)->setSex($sex)->save();
          $old = $current_year - $year + 1;
          
          $return_info = array(
              'id'=>$child->getId(),
              'year'=>$year,
              'month'=>$month,
              'sex'=>$child->getSexToString(),
              'old'=>$old
          );
          
          return $this->renderText(json_encode($return_info));
      }
      
  }
  
  //获取二级地级市
  public function executeCity(sfWebRequest $request){
      $province = $request->getParameter('key','北京');
      $citys = User::getAllCitys();
      return $this->renderText( (array_key_exists($province,$citys)) ? json_encode($citys[$province]) : '' );
  }
  
  public function executeSend_sms(sfWebRequest $request){
      if($request->isMethod('POST')){
          $phone = $request->getParameter('phone');
          
          if(strlen($phone) != 11){
              return $this->renderText("手机号码错误！请重新填写");
          }else{
            $has_user = Doctrine::getTable('User')->findOneByPhone($phone);  
            
            if($has_user){
                return $this->renderText("手机号已经注册");
            }
            
            $code = rand(111111, 999999);
            $sms = Doctrine::getTable('SmsMessage')->createQuery()->where('phone = ?',$phone)->andWhere('is_use = 0')->orderBy('created_at desc')->fetchOne();
            if($sms){
                $time = time();
                $created_time = strtotime($sms->getCreatedAt());
                if( ($time - $created_time) > 60 ){ //间隔60秒
                    $msg = $this->send_sms($code,$phone);
                    return $this->renderText($msg);
                }else{
                    return $this->renderText("验证码发送失败！验证码1分钟内不能重复发送");
                }
            }else{
                $msg = $this->send_sms($code,$phone);
                return $this->renderText($msg);
            }
          }
      }
  }
  
  protected function send_sms($code,$phone){
            $msg = '短信验证码：'.$code.'，请在5分钟内完成验证【有学教育】';
            $url = "http://sms.bechtech.cn/Api/send/data/json?accesskey=3585&secretkey=29751faf48356fb629fb902fceba4ed4a83415d3&mobile=".$phone."&content=".urlencode($msg);  
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $dom = curl_exec($ch);
            curl_close($ch);
            $arr = json_decode($dom,true); //格式化返回数组
//            var_dump($arr);
//            exit();
             if($arr['result']=='01'){
                 $sms = new SmsMessage();
                 $sms->setPhone($phone)->setCode($code)->setIsUse(0)->save();
                 return "验证码发送成功！请查收";
             }else{
                 return "验证码发送失败！请与管理员联系";
            }
  }
  
}
